﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Windows;
using System.Windows.Data;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YCAEKAPPR : DocumentBase
    {
        #region-------------Properties-----------------------
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        public ITXEXRPT ITXEXRPT;
        BindingListCollectionView cvEKVRECH
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgEKVRECH.ItemsSource);
            }
        }
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public DataSet dsResult;
        public YCAEKAPPRData m_Data;
        public DataSet dsParamaters;
       
        bool IsSupplierLoded = false;
        public string PrnType = "EXCEL";

        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }

        #region=====vwLIEFDAT=======
        CollectionViewSource vwLIEFDAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwLIEFDAT");
            }
        }
        DataRow dwLIEFDAT
        {
            get
            {
                if (vwLIEFDAT.View == null)
                    return null;
                if ((DataRowView)vwLIEFDAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLIEFDAT.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwLIEFDAT=======
        CollectionViewSource vwEKVRECH
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKVRECH");
            }
        }
        DataRow dwEKVRECH
        {
            get
            {
                if (vwEKVRECH.View == null)
                    return null;
                if ((DataRowView)vwEKVRECH.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKVRECH.View.CurrentItem).Row;
            }
        }
        #endregion

        #region=====vwEKKOPF=======
        CollectionViewSource vwEKKOPF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKKOPF");
            }
        }
        DataRow dwEKKOPF
        {
            get
            {
                if (vwEKKOPF.View == null)
                    return null;
                if ((DataRowView)vwEKKOPF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKKOPF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwEKPOS=======
        CollectionViewSource vwEKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEKPOS");
            }
        }
        DataRow dwEKPOS
        {
            get
            {
                if (vwEKPOS.View == null)
                    return null;
                if ((DataRowView)vwEKPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEKPOS.View.CurrentItem).Row;
            }
        }
        #endregion

        bool IsChkEKPBEKZ
        {
            get
            {
                if (ChkEKPBEKZ.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkEKPBEKZ.IsChecked = true;
                }
                else
                {
                    ChkEKPBEKZ.IsChecked = false;
                }
            }
        }
        bool IsChkEKPKNTRNRL
        {
            get
            {
                if (ChkEKPKNTRNRL.IsChecked == true)
                {
                    return true;
                }
                return false;
            }
            set
            {
                if (value)
                {
                    ChkEKPKNTRNRL.IsChecked = true;
                }
                else
                {
                    ChkEKPKNTRNRL.IsChecked = false;
                }
            }
        }
        public string KRS
        {
            get
            {
                return m_Data.Right("  " + txtABPAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtABPAUFKRS.Text = value;
            }
        }
        public string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtABPAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtABPAUFLFD.Text = value;
            }
        }
        #endregion
        public YCAEKAPPR()
        {
            InitializeComponent();
            this.Name = "采购单审核";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            dicParamater["blBuildCellMastrix"] = false;
            base.SetUp(dicParamater);
            InitializeComponent();
            this.dicParamater = dicParamater;
            OracleDB = (OracleConnection)dicParamater["OracleDB"];

            proxy = (IntexReptServBLClient)dicParamater["proxy"];
            m_Data = new YCAEKAPPRData(OracleDB, proxy);
            m_Data.UserID = Helpers.Helper.Left((string)dicParamater["User"] + "       ", 8);
            txtDate.Text= m_Data.year + m_Data.month;
            txtABPAUFKRS.Text = "";
            txtABPAUFLFD.Text = "";
            IsChkEKPBEKZ = true;
            IsChkEKPKNTRNRL = false;
            btnApprove.IsEnabled = false;
            btnCANCEL.IsEnabled = false;
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {

                if (!IsSupplierLoded)
                {
                    SetData.Merge(m_Data.LoadSupplier());
                    IsSupplierLoded = true;
                }

                vwEKKOPF.View.CurrentChanged += vwEKKOPF_CurrentChanged;
                vwLIEFDAT.View.CurrentChanged += vwLIEFDAT_CurrentChanged;
                vwEKPOS.View.CurrentChanged += vwEKPOS_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }

        void vwEKPOS_CurrentChanged(object sender, EventArgs e)
        {
            cvEKVRECH.CustomFilter = null;
            if (dwEKPOS == null)
                return;
            string ordernum = Helpers.Helper.Left(dwEKPOS["EKPAUFKRS"].ToString() + "-" + dwEKPOS["EKPAUFLFD"].ToString() + "-" + dwEKPOS["EKPAUFPOS"].ToString() + "                       ", 23);
            cvEKVRECH.CustomFilter = "EKVFILLER='" + ordernum + "'";
        }

        void vwLIEFDAT_CurrentChanged(object sender, EventArgs e)
        {
            if (dwLIEFDAT == null)
                return;

            DataSet Result = new DataSet();
            Result = m_Data.GetOrderBySupplier(dwLIEFDAT);
            SetData.EKKOPF.Clear();
            SetData.Merge(Result, false, MissingSchemaAction.Add);
        }

        void vwEKKOPF_CurrentChanged(object sender, EventArgs e)
        {
            DataSet Result = new DataSet();
            DataRow dwInput;
            dwInput = dwEKKOPF;
            if (dwInput == null)
            {
                return;
            }
            Result = m_Data.BuildData(dwInput);
            Set4ITX.Clear();
            Set4ITX.Merge(Result, false, MissingSchemaAction.Add);
        }
        public void btnQuery_Click(object sender, EventArgs e)
        {
            DataSet Result = new DataSet();
            DataRow dwInput;
            dwInput = dwEKKOPF;
            try
            {
                if (dwInput == null)
                {
                    if (LFD.Trim() == "0000000")
                        return;
                    dwInput = SetData.EKPOS.NewRow();
                    dwInput["EKPMANDANT"] = "00";
                    dwInput["EKPAUFKRS"] = KRS;
                    dwInput["EKPAUFLFD"] = LFD;
                }
                /*
                if (IsChkEKPBEKZ)//已经确认数量，未付款
                {
                    dwInput["EKPBEKZ"] = "'N'";
                    //IsChkALL = false;
                    dwInput["EKPKNTRNRL"] = " ";
                }
                //if (IsChkALL)//未付款，未确认数量
                {
                   // dwInput["EKPBEKZ"] = "' '";
                   // IsChkEKPBEKZ = false;
                 //   dwInput["EKPKNTRNRL"] = " ";
               // }
                if (IsChkEKPKNTRNRL)//已经付款
                {
                    dwInput["EKPBEKZ"] = "'N'";
                    //IsChkALL = false;
                    dwInput["EKPKNTRNRL"] = "NOT";
                    btnApprove.IsEnabled = false;
                    btnCANCEL.IsEnabled = true;

                }
                else
                {
                    btnApprove.IsEnabled = true;
                    btnCANCEL.IsEnabled = false;
                }*/
                dwInput["EKPBEKZ"] = "' '";
                IsChkEKPBEKZ = false;
                dwInput["EKPKNTRNRL"] = " ";
                btnApprove.IsEnabled = true;
                btnCANCEL.IsEnabled = true;
                Result = m_Data.BuildData(dwInput);
                Set4ITX.Clear();
                Set4ITX.Merge(Result);
                SetData.EKVRECH.Clear();
                SetData.Merge(Set4ITX.EKVRECH);
                if (vwEKPOS.View != null)
                {
                    vwEKPOS.View.MoveCurrentToFirst();
                }
                if (vwEKVRECH.View != null)
                {
                    vwEKVRECH.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void StartApprove(DataRow dwInput)
        {
            if (dwInput == null)
            {
                MessageBox.Show("请选择一条记录");
                return;
            }
            DataSet Result = new DataSet();
            OracleCommand or1 = OracleDB.CreateCommand();
            string orderno = Helpers.Helper.Left(dwInput["EKPAUFKRS"].ToString() + "-" + dwInput["EKPAUFLFD"].ToString() + "-" + dwInput["EKPAUFPOS"].ToString() + "                       ", 23);
            or1.CommandText = "SELECT COUNT(1) AS AA FROM EKVRECH  "
                        + " WHERE EKVMANDANT='00'  AND EKVFILLER = '" + orderno + "' "
                        ;
            Result = m_Data.Connect2Proxy(or1);
            Result.Tables[0].TableName = "T_EKVRECH";
            string v_i = "";
            foreach (DataRow dw in Result.Tables["T_EKVRECH"].Rows)
            {
                v_i = dw["AA"].ToString();
                if (v_i == "0")
                {
                    DataRow dwData = SetData.EKPOS.NewRow();
                    dwData["EKPMANDANT"] = dwInput["EKPMANDANT"];
                    dwData["EKPAUFKRS"] = dwInput["EKPAUFKRS"];
                    dwData["EKPAUFLFD"] = dwInput["EKPAUFLFD"];
                    dwData["EKPAUFPOS"] = dwInput["EKPAUFPOS"];
                    dwData["EKPBEKZ"] = "N";
                    dwData["EKPKNTRNRL"] = m_Data.day + "." + m_Data.month + "." + Helpers.Helper.Right(m_Data.year, 2) + "       ";
                    m_Data.INTEXDBC.UpdateEKPOS(dwData, 4);
                }
                else
                {
                    string syear = Helpers.Helper.Right(m_Data.year, 2);
                    string ordernum = Helpers.Helper.Left(dwInput["EKPAUFKRS"].ToString() + "-" + dwInput["EKPAUFLFD"].ToString() + "-" + dwInput["EKPAUFPOS"].ToString() + "                       ", 23);
                    var query = from DataRow row in Set4ITX.EKVRECH.AsEnumerable()
                                where row["EKVFILLER"].ToString() == ordernum
                                && row["EKVKIR"].ToString() == " "
                                select row;

                    foreach (DataRow row in query)
                    {
                        row["EKVKIR"] = "K";
                        row["EKVAENDZL"] = 2;
                        row["EKVAENDBEN"] = m_Data.UserID;
                        row["EKVAENDDAT"] = m_Data.date;
                        m_Data.INTEXDBC.UpdateEKVRECH(row);
                    }
                    decimal applied = 0;
                    query = from DataRow row in Set4ITX.EKVRECH.AsEnumerable()
                            where row["EKVFILLER"].ToString() == ordernum
                            select row;
                    foreach (DataRow row in query)
                    {
                        applied += System.Convert.ToDecimal(row["EKVBETRAG"].ToString());
                    }
                    if (applied == 0)
                        continue;
                    decimal ekpwe1 = System.Convert.ToDecimal(dwEKPOS["EKPWE1"].ToString());
                    
                    if (Math.Round(ekpwe1 - applied, 0) <= 0)
                    {
                        DataRow dwData = SetData.EKPOS.NewRow();
                        dwData["EKPMANDANT"] = dwInput["EKPMANDANT"];
                        dwData["EKPAUFKRS"] = dwInput["EKPAUFKRS"];
                        dwData["EKPAUFLFD"] = dwInput["EKPAUFLFD"];
                        dwData["EKPAUFPOS"] = dwInput["EKPAUFPOS"];
                        dwData["EKPBEKZ"] = "N";
                        dwData["EKPKNTRNRL"] = m_Data.day + "." + m_Data.month + "." + Helpers.Helper.Right(m_Data.year, 2) + "       ";
                        m_Data.INTEXDBC.UpdateEKPOS(dwData, 4);
                    }
                }
            }
            //vwEKPOS.View.MoveCurrentToNext();
        }
        public void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                if (dwEKPOS == null)
                {
                    MessageBox.Show("必须选中一行采购单");
                    return;
                }
                foreach (DataRow dwData in Set4ITX.ICC_EKPOS.Rows)
                {
                    StartApprove(dwData);
                }
                //vwEKPOS.View.MoveCurrentToNext();
                //btnQuery_Click(null,null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnCANCEL_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwEKPOS == null)
                    return;
                /*string ordernum = Helpers.Helper.Left(dwEKPOS["EKPAUFKRS"].ToString() + "-" + dwEKPOS["EKPAUFLFD"].ToString() + "-" + dwEKPOS["EKPAUFPOS"].ToString() + "                       ", 23);
                cvEKVRECH.CustomFilter = "EKVFILLER='" + ordernum + "' AND EKVKIR='K' ";
                vwEKVRECH.View.MoveCurrentTo(-1);*/
                //if (vwEKVRECH.View == null)
                //{
                //MessageBox.Show("请选择一个付款行!");
                //return;
                DataSet Result = new DataSet();
                OracleCommand or1 = OracleDB.CreateCommand();
                string orderno = Helpers.Helper.Left(dwEKPOS["EKPAUFKRS"].ToString() + "-" + dwEKPOS["EKPAUFLFD"].ToString() + "-" + dwEKPOS["EKPAUFPOS"].ToString() + "                       ", 23);
                or1.CommandText = "SELECT COUNT(1) as AA FROM EKVRECH  "
                            + " WHERE EKVMANDANT='00'  AND EKVFILLER = '" + orderno + "' "
                            ;
                Result = m_Data.Connect2Proxy(or1);
                Result.Tables[0].TableName = "T_EKVRECH";
                string v_i = "";
                foreach (DataRow dw in Result.Tables["T_EKVRECH"].Rows)
                {
                    v_i = dw["AA"].ToString();
                    if (v_i == "0")
                    {
                        DataRow dwData = SetData.EKPOS.NewRow();
                        dwData["EKPMANDANT"] = dwEKPOS["EKPMANDANT"];
                        dwData["EKPAUFKRS"] = dwEKPOS["EKPAUFKRS"];
                        dwData["EKPAUFLFD"] = dwEKPOS["EKPAUFLFD"];
                        dwData["EKPAUFPOS"] = dwEKPOS["EKPAUFPOS"];
                        dwData["EKPBEKZ"] = "N";
                        dwData["EKPKNTRNRL"] = "               ";
                        m_Data.INTEXDBC.UpdateEKPOS(dwData, 4);
                        btnQuery_Click(null, null);
                    }
                    else
                    {
                        if (vwEKVRECH.View == null)
                        {
                            MessageBox.Show("请选择一个付款行!");
                            return;
                        }
                        if (dwEKVRECH["EKVKIR"].ToString() != "K")
                        {
                            MessageBox.Show("请选择一个已付款行!");
                            return;
                        }
                        dwEKVRECH["EKVKIR"] = " ";
                        dwEKVRECH["EKVAENDZL"] = 3;
                        dwEKVRECH["EKVAENDBEN"] = m_Data.UserID;
                        dwEKVRECH["EKVAENDDAT"] = m_Data.date;
                        m_Data.INTEXDBC.UpdateEKVRECH(dwEKVRECH);
                        vwEKVRECH.View.MoveCurrentTo(-1);
                        DataRow dwData = SetData.EKPOS.NewRow();
                        dwData["EKPMANDANT"] = dwEKPOS["EKPMANDANT"];
                        dwData["EKPAUFKRS"] = dwEKPOS["EKPAUFKRS"];
                        dwData["EKPAUFLFD"] = dwEKPOS["EKPAUFLFD"];
                        dwData["EKPAUFPOS"] = dwEKPOS["EKPAUFPOS"];
                        dwData["EKPBEKZ"] = "N";
                        dwData["EKPKNTRNRL"] = "               ";
                        m_Data.INTEXDBC.UpdateEKPOS(dwData, 4);
                        btnQuery_Click(null, null);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void btnQueryHistory_Click(object sender, RoutedEventArgs e)
        {
            string mYear = txtDate.Text.ToString().Trim();
            DataRow dwData = SetData.EKVRECH.NewRow();
            dwData["EKVAENDDAT"] = mYear;
            DataSet SResult = m_Data.INTEXDBC.QueryEKVRECH(dwData, 4);
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                row["SELLER"] = Helpers.Helper.Convert8859P1ToGB2312(row["SELLER"].ToString().Trim());
                row["SELLERNAME"] = Helpers.Helper.Convert8859P1ToGB2312(row["SELLERNAME"].ToString().Trim());
                row["EXFTY"] = Helpers.Helper.Convert8859P1ToGB2312(row["EXFTY"].ToString().Trim());
                row["FACNAME"] = Helpers.Helper.Convert8859P1ToGB2312(row["FACNAME"].ToString().Trim());
                row["FSABEZ"] = Helpers.Helper.Convert8859P1ToGB2312(row["FSABEZ"].ToString().Trim());
                row["EXART"] = Helpers.Helper.Convert8859P1ToGB2312(row["EXART"].ToString().Trim());
                row["EXCOLOR"] = Helpers.Helper.Convert8859P1ToGB2312(row["EXCOLOR"].ToString().Trim());
                row["CDES"] = Helpers.Helper.Convert8859P1ToGB2312(row["CDES"].ToString().Trim());
                if (row["MTYPE"].ToString() == "T")
                {
                    row["MATTYP"] = "辅料";
                    continue;
                }
                switch (row["FSSZUSCHN"].ToString().Trim())
                {
                    case "J":
                        row["MATTYP"] = "主面料";
                        break;
                    case "":
                        row["MATTYP"] = "里布";
                        break;
                    case "C":
                        row["MATTYP"] = "衬布";
                        break;
                    case "N":
                        row["MATTYP"] = "配布";
                        break;
                }
            }
            SetData.Clear();
            SetData.Merge(SResult);
        }

        private void btnPrintHistory_Click(object sender, RoutedEventArgs e)
        {          
            ITXEXRPT.dsSource = SetData; 
            ITXEXRPT.DocType = app.company + "EKPAID";
            ITXEXRPT.strExcelFile = app.company + @"\YCAEK.xls";
            string filename = ITXEXRPT.WriteExcelReport(); 
        }
    }
}
